package com.atom.common.util;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;

import org.apache.log4j.Logger;

import com.atom.common.CommonConstant;
import com.atom.common.exception.AvensHtmlGenerateException;

import freemarker.core.ParseException;
import freemarker.template.Configuration;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.Template;
import freemarker.template.TemplateNotFoundException;

public class CommonHtmlGenerateUtil {
  
  static Logger logger = Logger.getLogger(CommonHtmlGenerateUtil.class);
  
  private static  Configuration config = null;
  
  private static String FTL_ROOT = GlobalConfigReader.getStringValue(CommonConstant.FTL_ROOT);
  private static String FTL_OUTPUT = GlobalConfigReader.getStringValue(CommonConstant.FTL_OUTPUT);

  private static void init() {
    config = new Configuration(Configuration.VERSION_2_3_24);
    //config.setDirectoryForTemplateLoading(new File(FTL_ROOT));
    config.setClassForTemplateLoading(CommonHtmlGenerateUtil.class, FTL_ROOT);
    config.setDefaultEncoding("UTF-8");
  }

  public static String generate(Map<String, Object> map, String templateName, String fileName) {

    init();

    Writer out = null;
    try{  
      //获得模板  
      logger.info("TemplateName:" + templateName);
      Template template = getTemplate(templateName);
      System.out.println(template.getName());
      //生成文件
      String filePath = FTL_OUTPUT + fileName + ".html";
      logger.info("OutputFilePath:" + filePath);
      out = new OutputStreamWriter(new FileOutputStream(filePath));
      template.process(map, out);
      out.flush();     
      return filePath;
    } catch (Exception e) {  
      throw new AvensHtmlGenerateException("Generate failed where fileName = " + fileName);
    } finally {  
      try {  
        out.close();  
        out = null;  
      } catch (IOException e) {  
      }  
    }  
  }
  
  private static Template getTemplate(String templateName) {
    try {
      return config.getTemplate(templateName, "utf-8");      
    } catch (TemplateNotFoundException e) {
      throw new AvensHtmlGenerateException("TemplateNotFoundException");
    } catch (MalformedTemplateNameException e) {
      throw new AvensHtmlGenerateException("MalformedTemplateNameException");
    } catch (ParseException e) {
      throw new AvensHtmlGenerateException("ParseException");
    } catch (IOException e) {
      throw new AvensHtmlGenerateException("IOException");
    }
  }

}
